//
//  ClassifyDetailViewController.m
//  B2C
//
//  Created by xiaowu on 2017/8/3.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "ClassifyDetailViewController.h"
#import "HomeTableViewCell.h"
#import "TitleSelectView.h"
#import "GoodDetailViewController.h"
#import "CommodityModel.h"

#import "PageNationModel.h"
#import "ClassifyDetailItemModel.h"

@interface ClassifyDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) HomeTableViewCell *firstCell;
@property (nonatomic, strong) TitleSelectView *titleView;

@property (nonatomic, strong) NSMutableArray *dataArr;

@property (weak, nonatomic) IBOutlet UIView *tempView;
@end

@implementation ClassifyDetailViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.navigationItem.leftBarButtonItem = nil;
        _index = 0;
        _dataArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureCollectionItemArr];
    [self configureUI];
    [self loadDataWithIndex:self.index withCell:nil item:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.titleView.frame = CGRectMake(0, 0, ScreenWidth, self.titleView.height);
    self.collectionView.frame = CGRectMake(0, self.titleView.height, self.view.width, self.view.height - self.titleView.height);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[self.navigationController.navigationBar subviews].firstObject.subviews.firstObject setAlpha:0.0];
    [self.view bringSubviewToFront:self.tempView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[self.navigationController.navigationBar subviews].firstObject.subviews.firstObject setAlpha:1.0];
}

#pragma mark - Method
- (void)configureUI {
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.collectionView];
    
    [self.titleView setupWithTitleStrsArr:[self getTitlesStr:self.titleArr] withIndex:self.index];
    if (self.index > 0) {
        [self.tempView setHidden:YES];
    } else {
        [self.tempView setHidden:NO];
    }
    
    self.collectionView.bounces = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self.collectionView scrollRectToVisible:CGRectMake(self.index * self.collectionView.width, self.titleView.height, self.collectionView.width, self.collectionView.height) animated:NO];
    });
    
    __weak typeof(self) weakSelf = self;
    self.titleView.block = ^(NSInteger index) {
        [weakSelf.collectionView scrollRectToVisible:CGRectMake(index * weakSelf.collectionView.width, weakSelf.titleView.height, weakSelf.collectionView.width, weakSelf.collectionView.height) animated:YES];
        [weakSelf setIndexAndLoadData:index];
        if (index > 0) {
            [weakSelf.tempView setHidden:YES];
        } else {
            [weakSelf.tempView setHidden:NO];
        }
    };
}

- (void)setIndexAndLoadData:(NSInteger)index {
    self.index = index;
    [self loadDataWithIndex:index withCell:nil item:nil];
}

- (NSMutableArray *)getTitlesStr:(NSArray *)arr {
    NSMutableArray *title = [NSMutableArray array];
    
    for (ClassifySecondModel *model in self.titleArr) {
        [title addObject:model.gtcname];
    }
    
    return title;
}

- (void)configureCollectionItemArr {
    for (ClassifySecondModel *titleModel in self.titleArr) {
        ClassifyDetailItemModel *itemModel = [[ClassifyDetailItemModel alloc] init];
        [self.dataArr addObject:itemModel];
    }
}

- (void)setDataToArr:(NSArray *)arr withNationModel:(PageNationModel *)pageNationModel Index:(NSInteger)index withCell:(HomeTableViewCell *)cell {
    ClassifyDetailItemModel *itemModel = [self.dataArr objectAtIndex:index];
    if (pageNationModel.pageNumber == 1) {
        [itemModel.dataArr removeAllObjects];
    }
    itemModel.pageNationModel = pageNationModel;
    [itemModel.dataArr addObjectsFromArray:arr];
    
    if (cell) {
        [cell setShowArr:itemModel.dataArr withPageNation:pageNationModel];
    } else {
        [self.collectionView reloadData];
    }
}

- (void)refreshWithIndex:(NSInteger)index withCell:(HomeTableViewCell *)cell andHeader:(BOOL)header {
    ClassifyDetailItemModel *itemModel = [self.dataArr safeObjectAtIndex:index];
    if (header) {
        itemModel.pageNationModel.pageNumber = 1;
    } else {
        itemModel.pageNationModel.pageNumber += 1;
    }
    
    [self loadDataWithIndex:index withCell:cell item:itemModel];
}

#pragma mark - Network
- (void)loadDataWithIndex:(NSInteger)index withCell:(HomeTableViewCell *)cell item:(ClassifyDetailItemModel *)itemModel {
    ClassifySecondModel *model = [self.titleArr safeObjectAtIndex:index];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:model.gtcid forKey:@"gtcid"];
    [parameters safeSetObject:itemModel.pageNationModel ? @(itemModel.pageNationModel.pageNumber) : @"1" forKey:@"pageNumber"];
    [parameters safeSetObject:@"10" forKey:@"pageSize"];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Goods parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            NSDictionary *pagenation = [responseDic safeJsonObjectForKey:@"pagenation"];
            PageNationModel *pageNationModel = [PageNationModel mj_objectWithKeyValues:pagenation];
            NSMutableArray *dataArr = [NSMutableArray array];
            
            for (NSDictionary *modelDic in data) {
                CommodityModel *model = [CommodityModel mj_objectWithKeyValues:modelDic];
                [dataArr addObject:model];
            }
            [weakSelf setDataToArr:dataArr withNationModel:pageNationModel Index:index withCell:cell];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD showError:weakSelf.view title:@"" code:nil animated:YES];
        
    } isNeedCache:NO];
}


//- (void)loadDataWithIndex:(NSInteger)index {
//    ClassifySecondModel *model = [self.titleArr safeObjectAtIndex:index];
//    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//    [parameters safeSetObject:model.gtcid forKey:@"gtcid"];
//    [parameters safeSetObject:@"1" forKey:@"pageNumber"];
//    [parameters safeSetObject:@"10" forKey:@"pageSize"];
//    
//    [MBProgressHUD showHUDProgress:self.view animated:YES];
//    
//    __weak typeof(self) weakSelf = self;
//    [MYAFNetworking POST:URL_Get_Goods parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
//        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
//        NSDictionary *responseDic = responseObject;
//        NSString *code = [responseDic safeStringForKey:@"code"];
//        if (code && [code isEqualToString:@"200"]) {
//            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
//            NSDictionary *pagenation = [responseDic safeJsonObjectForKey:@"pagenation"];
//            PageNationModel *pageNationModel = [PageNationModel mj_objectWithKeyValues:pagenation];
//            NSMutableArray *dataArr = [NSMutableArray array];
//            
//            for (NSDictionary *modelDic in data) {
//                CommodityModel *model = [CommodityModel mj_objectWithKeyValues:modelDic];
//                [dataArr addObject:model];
//            }
//            [weakSelf setDataToArr:dataArr withNationModel:pageNationModel Index:index withCell:nil];
//        } else {
//            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
//        [MBProgressHUD showError:weakSelf.view title:@"" code:nil animated:YES];
//        
//    } isNeedCache:NO];
//}

#pragma mark - Action


#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.titleArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    __weak typeof(self) weakSelf = self;
    HomeTableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"tableViewCell" forIndexPath:indexPath];

    ClassifyDetailItemModel *itemModel = [self.dataArr safeObjectAtIndex:indexPath.row];
    
    [cell setShowArr:itemModel.dataArr withPageNation:itemModel.pageNationModel];
    cell.block = ^(NSString *commodityId) {
        NSLog(@"%@", commodityId);
        GoodDetailViewController *goodVC = [[GoodDetailViewController alloc] init];
        goodVC.gid = commodityId;
        [weakSelf.navigationController pushViewController:goodVC animated:YES];
    };
    
    __weak typeof(cell) weakCell = cell;
    cell.headerRefresh = ^{
        [weakSelf refreshWithIndex:indexPath.row withCell:weakCell andHeader:YES];
    };
    cell.footerRefresh = ^{
        [weakSelf refreshWithIndex:indexPath.row withCell:weakCell andHeader:NO];
    };
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.view.width, self.view.height - self.titleView.height);
}


#pragma mark - UIScrollViewDeleagte
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.collectionView) {
        return;
    }
    CGFloat x = scrollView.contentOffset.x;
    CGFloat page = x / (self.view.width);
    NSInteger index = (page + 0.3) / 1;
    [self.titleView setToShowIndex:index withAnimation:YES];
    [self setIndexAndLoadData:index];
    NSLog(@"scrollViewDidEndDecelerating: %f, index:%ld", page, (long)index);
    if (index > 0) {
        [self.tempView setHidden:YES];
    } else {
        [self.tempView setHidden:NO];
    }
}

#pragma mark -- Getters
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = CGSizeMake(self.view.width, self.view.height - self.titleView.height);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // 横向
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.pagingEnabled = YES;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"tableViewCell"];
    }
    return _collectionView;
}


- (TitleSelectView *)titleView {
    if (!_titleView) {
        _titleView = [[TitleSelectView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 32)];
        _titleView.backgroundColor = [UIColor NavBarColor];
    }
    return _titleView;
}

- (NSMutableArray *)getTestData {
    NSMutableArray *arr = [NSMutableArray array];
    CommodityModel *model = [[CommodityModel alloc] init];
    
    for (NSInteger i = 0; i < 20; i++) {
        [arr addObject:model];
    }
    
    return arr;
}

@end
